package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 *
 * 切面代理
 *
 * @author: Mr.Zhou
 * @create: 2018-10-25 16:03
 **/
public class AspectProxy implements Proxy{

    private static final Logger LOGGER= LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public Object dePorxy(ProxyChain proxyChain) throws Throwable {
        Object result=null;
        Class<?> cls=proxyChain.getTargetClass();
        Method method=proxyChain.getTargetMethod();
        Object[] params=proxyChain.getMethodParams();
        begin();
        try {
            if(interceptor(cls,method,params)){
                before(cls,method,params);
                result=proxyChain.doProxyChain();
                after(cls,method,params,result);
            }

        }catch (Exception e){
            LOGGER.error("proxy failure",e);
            error(cls,method,params,e);
            throw e;
        }finally {
            end();
        }
        return result;
    }

    public void begin(){}

    public boolean interceptor(Class<?> cls,Method method,Object[] params)throws Throwable{
        return true;
    }

    public void before(Class<?> cls,Method method,Object[] params)throws Throwable{}

    public void after(Class<?> cls,Method method,Object[] params,Object result)throws Throwable{}

    public void error(Class<?> cls,Method method,Object[] params,Throwable e)throws Throwable{}

    public void end(){}
}
